package com.example.demo.controller;


import com.example.demo.entity.Product;
import com.example.demo.service.impl.ProductServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;


@RestController
public class UploadController {
    @Autowired
    public ProductServiceImpl productService;

    @PostMapping("/upload")
    public String upload(@RequestBody MultipartFile file) {
        if(file.isEmpty()){
            return "文件不能为可空！";
        }

        File folder = new File("D:\\Idea\\project\\demo\\src\\main\\resources\\static\\images\\");
        if (!folder.exists()) {
            folder.mkdirs();
        }
        Date date = new Date();

        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

        String str = format.format(date);
        String oldName = file.getOriginalFilename();
        String newName = oldName.substring(0,oldName.indexOf("."))+str+oldName.substring(oldName.lastIndexOf("."));
        File newFile = new File(folder, newName);
        try {
            //保存文件，返回文件路径
            file.transferTo(newFile);
            return folder + newName;
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        return "error";
    }
    @PostMapping("/uploadInfo")
    public String uploadInfo(@RequestBody Product product) {
        if (product.toString() != null) {
            productService.add(product);
            return "success";
        }
        return "false";
    }
}